package cn.hnucm.config;

import cn.hnucm.service.Impl.LoginValidateAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author:liweihua
 * @Description:    SpringSecurity的配置类，用来判断请求的
 * @Date: 10:22$ 2021/12/18/018$
 * @Modified:
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginValidateAuthenticationProvider loginValidateAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这里要设置自定义认证
        auth.authenticationProvider(loginValidateAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
                antMatchers("/auth/sign").permitAll()
                .anyRequest().authenticated();
        http.formLogin()
                //自定义表单提交
                .usernameParameter("userAccount")
                .passwordParameter("userPassword")
                //前端请求/auth/login，然后进入UserDetailsServiceImpl去认证
                .loginProcessingUrl("/auth/login")
                .successForwardUrl("/success")
                .failureForwardUrl("/failure")
                .and().csrf().disable();

    }
    //注册组件，UserDetailsServiceImpl需要用到BCryptPasswordEncoder
    @Bean
    public PasswordEncoder getPw(){
        return new BCryptPasswordEncoder();
    }
}
